package uk.co.accolade.clash.app.intellij.toolwindow;

import com.intellij.openapi.application.Application;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.IconUtil;
import uk.co.accolade.clash.app.FileNode;
import uk.co.accolade.clash.app.UserNode;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
import java.io.File;
import java.net.URL;

public class ClashIconRenderer extends DefaultTreeCellRenderer {

    private static final String USER_ICON = "/images/User.png";
    private static final String USER_ICON_DESCRIPTION = "User";

    private ImageIcon userIcon;
    private Project project;
    private Application application;
    private LocalFileSystem localFileSystem;

    public ClashIconRenderer( Project project, Application application, LocalFileSystem localFileSystem ) {
        this.project = project;
        this.application = application;
        this.localFileSystem = localFileSystem;
        userIcon = createUserIcon();        
    }

    public Component getTreeCellRendererComponent(JTree tree,
      Object value,boolean sel,boolean expanded,boolean leaf,
      int row,boolean hasFocus) {

        super.getTreeCellRendererComponent(tree, value, sel,
          expanded, leaf, row, hasFocus);

        Object nodeObj = ((DefaultMutableTreeNode)value).getUserObject();
        if( nodeObj instanceof UserNode ) {
            setIcon( userIcon );
        } else if( nodeObj instanceof FileNode ) {
            File file = new File( project.getBaseDir().getPath() + nodeObj.toString() );
            final VirtualFile virtualFile = localFileSystem.findFileByIoFile( file );
            if( virtualFile != null ) {
                application.runReadAction( new Runnable() {
                    public void run() {
                        setIcon( IconUtil.getIcon( virtualFile, 0, project ) );
                    }
                });
            }
        }
        return this;
    }


    private ImageIcon createUserIcon() {
        return createImageIcon( USER_ICON, USER_ICON_DESCRIPTION );
    }

    private ImageIcon createImageIcon( String path, String description ) {
        URL imgURL = getClass().getResource( path );
        if( imgURL != null ) {
            return new ImageIcon( imgURL, description );
        } else {
            System.err.println( "Couldn't find file: " + path );
            return null;
        }
    }
    
}